<?php
namespace app\mp\admin;

use app\system\admin\Admin;
use app\common\service\OrderMaterial as OrderMaterialService;
use app\common\service\Material as MaterialService;
use app\common\service\Order as OrderService;
use app\common\service\StockLog as StockLogService;
use app\common\service\DistributingFeed as DistributingFeedService;
use app\common\service\MaterialReturn as MaterialReturnService;

/**
 * 辅料仓库
 * @author King
 *
 */
class Stock extends Admin
{

    public function initialize() {
    	parent::initialize();
    }

    /**
     * 辅料列表
     *
     * @author KING
     * @date 2020年7月14日
     *
     */
    public function index()
    {
    	if ($this->request->isAjax()) {
    		$where      = $data = [];
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);
    		$materialName    = $this->request->param('material_name/s');
    		$materialSku    = $this->request->param('material_sku/s');

    		if ($materialName != '') {
    			$where[] = ['material_id', 'in', db('material')->where('name', 'like', "%{$materialName}%")->column('id')];
    		}
    		if ($materialSku != '') {
    			$where[] = ['material_id', 'in', db('material')->where('material_sku', '=', $materialSku)->column('id')];
    		}

    		$order = 'update_time desc';
    		$data['data'] = db('stock')->where($where)->page($page)->limit($limit)->order($order)->select();
    		$materialService = new MaterialService();
    		foreach ($data['data'] as $k => $v) {
    			$data['data'][$k]['mInfo'] = $materialService->getInfoById($v['material_id'], 'name,material_sku');
    			$map = [
    				['type', '=', 1],
    				['stock_id', '=', $v['id']],
					['left_num', '>', 0],
    			];
    			$data['data'][$k]['amount'] = round(db('stock_log')->where($map)->sum('amount'), 2);
    		}

    		$data['count'] = db('stock')->where($where)->count('id');
    		$data['code'] = 0;
    		$data['msg'] = '';
    		return json($data);
    	}

    	$assign = [];
    	return $this->assign($assign)->fetch();
    }

    /**
     * 操作日志
     *
     * @author KING
     * @date 2020年7月8日
     *
     * @return \think\response\Json|string
     */
    public function log()
    {
    	$factoryKV = getFactoryKV(true);
    	$id = $this->request->param('id/d', 0);
    	if ($this->request->isAjax()) {
    		$where      = $data = [];
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);

    		$where[] = ['stock_id', '=', $id];

    		$order = 'id desc';
    		$data['data'] = db('stock_log')->where($where)->page($page)->limit($limit)->order($order)->select();
    		foreach ($data['data'] as $k => $v) {
    			$data['data'][$k]['factory_name'] = arrayGet($factoryKV, $v['factory_id'], '');
    		}
    		$data['count'] = db('stock_log')->where($where)->count('id');
    		$data['code'] = 0;
    		$data['msg'] = '';
    		return json($data);
    	}

    	$assign = ['id' => $id];
    	return $this->assign($assign)->fetch();
    }

    /**
     * 辅料入库
     */
	public function add() {
		$factoryKV = getFactoryKV(true);
		$unitKV = getUnitKV();
		$materialService = new MaterialService();
		$orderMaterialService = new OrderMaterialService();
		$orderService = new OrderService();
		$stockLogService = new StockLogService();
		$distributingFeedService = new DistributingFeedService();

		if ($this->request->isPost()) {

			$postData = $this->request->post();
			$feedId = $this->request->param('feed_id/d', 0); // 补料单ID
			$materialSku = $this->request->param('material_sku/s');
			$clientOrdernum = $this->request->param('client_ordernum/s');
			$unit = $this->request->param('purchasing_unit/s');
			$stock = $this->request->param('stock/d', 0);
			$factoryId = $this->request->param('factory_id/d', 0);
			$unitPrice = $this->request->param('unit_price/d', 0);
			$amount = $this->request->param('amount/d', 0);
			$materialReturnId = $this->request->param('material_return_id/d', 0); // 退料进度Id

			$materialInfo = $materialService->getInfoBySku($materialSku);
			if (!$materialInfo) {
				$this->error('您输入的物料SKU不存在');
			}

			if ($clientOrdernum == '' && empty($factoryId)) {
				$this->error('工厂和订单号不能同时为空');
			}

			$orderInfo = [];
			if ($clientOrdernum != '') {
				$orderInfo = $orderService->getInfoByClientOrdernum($clientOrdernum);
				if (!$orderInfo) {
					$this->error('您输入的订单号不存在');
				}
				if ($orderInfo['factory_id']) $factoryId = $orderInfo['factory_id'];
			}

			try {
				db()->startTrans();
				$stockInfo = db('stock')->where('material_id', arrayGet($materialInfo, 'id', 0))->findOrEmpty();
				if ($stockInfo) {
					$stockId = 0;
					$arr['stock'] = $stockInfo['stock'] + $stock;
					$arr['unit'] = $unit;
					$arr['update_time'] = time();
					$res = db('stock')->where('id', $stockInfo['id'])->update($arr);
					if ($res !== false) $stockId = $stockInfo['id'];
				} else {
					$arr['material_id'] = $materialInfo['id'];
					$arr['stock'] = $stock;
					$arr['unit'] = $unit;
					$arr['create_time'] = $arr['update_time'] = time();
					$stockId = db('stock')->insertGetId($arr);
				}

				// 更新退料进度表状态，标记已入库
				if ($materialReturnId) {
					$upData = [
						'status' => 3,
						'duty_admin_id' => ADMIN_ID,
						'over_time' => time(),
					];
					db('material_return')->where('id', $materialReturnId)->update($upData);

					(new MaterialReturnService())->addLog($materialReturnId, 2);
				}

				if ($stockId) {
					$stockLog = [
						'type' => 1,
						'stock_id' => $stockId,
						'material_id' => $materialInfo['id'],
						'operate_num' => $arr['stock'],
						'left_num' => $arr['stock'],
						'unit_price' => $unitPrice ? : 0,
						'amount' => $amount ? : 0,
						'feed_id' => $feedId,
						'factory_id' => arrayGet($orderInfo, 'factory_id', 0),
						'order_id' => arrayGet($orderInfo, 'id', 0),
						'client_ordernum' => arrayGet($orderInfo, 'client_ordernum', 0),
						'sku' => arrayGet($orderInfo, 'sku', 0),
						'remark' => '新物料入库',
						'create_time' => time(),
						'update_time' => time(),
					];

					db('stock_log')->insertGetId($stockLog);

					if ($orderInfo) {
						$orderId = arrayGet($orderInfo, 'id', 0);
						// 1、补料单状态修改为完成；
						$feedUpdata = [
							'status' => 4,
							'update_time' => time(),
						];
						if ($feedId) {
							db('distributing_feed')->where('id', $feedId)->update($feedUpdata);
						} else {
							db('distributing_feed')->where('order_id', $orderId)->where('material_id', $materialInfo['id'])->update($feedUpdata);
						}

						// 2、重新检测订单物料库存，自动使用库存
						$feedRes = $distributingFeedService->useStock($materialInfo['id'], $orderId, false);

						/**
						 * ret=-1	该订单物料已采购完成
						 * ret=-2	该订单物料已采购在途中
						 * ret=0	服务异常
						 * ret=1	已成功使用库存完成该物料的采购
						 * ret=2	已生成采购任务单，请前往补料区查看
						 * ret=3	需手动再次发起补料
						 */
						if ($feedRes['ret'] == 0) {
							throw new \Exception($feedRes['msg']);
						}

						// 检测订单的所有辅料采购状态是否都已完成
						$orderCount = arrayGet($orderInfo, 'quantity', 0);
						$alist = $orderMaterialService->getListByOrderId($orderId, 'accessories');
						$allOver = true;
						foreach ($alist as $v) {
							$materialId = $v['material_id'];

							$materialDosageTotal = $orderCount*$v['material_dosage'];	// 总的用量

							// 已使用量
							$useNum = $stockLogService->getUseNum($materialId, $orderId);
							if ($useNum >= $materialDosageTotal) continue;
							else {
								$allOver = false;
								break;
							}
						}
						if ($allOver) {
							$upData = [
								'status' => 4,
								'update_time' => time(),
							];
							db('distributing')->where('order_id', arrayGet($materialInfo, 'id', 0))->update($upData);
						}

					}
				}

				$this->addOrderLog(arrayGet($orderInfo, 'client_ordernum', 0), arrayGet($orderInfo, 'client_ordernum', ''), "辅料[{$materialInfo['name']}]入库{$stock}");
				db()->commit();

				return $this->Json(1, '辅料入库成功', ['material_sku' => $materialSku, 'stock' => $stock, 'feed_id' => $feedId, 'material_return_id' => $materialReturnId]);
			} catch (\Exception $e) {
				db()->rollback();
				return $this->Json(0, '辅料入库失败'.$e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
			}

		}

		$assign = [
			'factoryKV' => $factoryKV,
			'unitKV' => $unitKV
		];
		$assign['_t'] = $this->request->param('_t/d', 0);
		$assign['mid'] = $this->request->param('mid/d', 0);
		$assign['feedId'] = $this->request->param('feed_id/d', 0); // 补料单ID
		$assign['materialReturnId'] = $this->request->param('material_return_id/d', 0); // 退料单ID
		$assign['materialSku'] = $this->request->param('material_sku/s');
		$assign['clientOrdernum'] = $this->request->param('client_ordernum/s');
		$assign['materialInfo'] = $materialService->getInfoBySku($assign['materialSku']);;
		$assign['orderInfo'] = $orderService->getInfoByClientOrdernum($assign['clientOrdernum']);

		if ($assign['materialInfo']) {
			$unit = db('stock')->where('material_id', $assign['materialInfo']['id'])->value('unit', '');
			if ($unit) $assign['unitKV'][$unit] = $unit;
		}

		$template = $this->request->param('template', 'add');
		return $this->assign($assign)->fetch($template);
	}

	/**
     * 辅料编辑
     */
	public function edit(){
		$id = $this->request->param('id/d', 0);
		$stockInfo = db('stock')->where('id', $id)->findOrEmpty();
		if ($this->request->isPost()) {
			$stock = $this->request->param('stock/d', 0);
			$arr['stock'] = $stock;
			$arr['update_time'] = time();
			$res = db('stock')->where('id', $id)->update($arr);
			if($res){
				return $this->Json(1, '操作成功');
			}else{
				return $this->Json(0, '操作失败');
			}
		}
		$assign=$stockInfo;
		$template = $this->request->param('template', 'edit');
		return $this->assign($assign)->fetch($template);
	}
}